package com.online.web.signature;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.online.web.domain.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.*;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test {

    @Autowired
    private RestTemplate restTemplate;

    private static final String URL = "http://219.151.11.5:11002/stage-api";
    private static final String TASK_API_ENDPOINT = "/minzheng/callTask";
    private static final String RESULT_API_ENDPOINT = "/minzheng/queryCallResult";
    private static final String SCENE_API_ENDPOINT = "/minzheng/queryActs";
    private static final String CREATE_SCENE_API_ENDPOINT = "/minzheng/createAct";
    private static final String PRIVATE_KEY = "2514d8a41c7bf5583ea570047a2836d2";
    private static final String APPID = "2";

    /**
     * 新建场景接口
     */
    @org.junit.Test
    public void createScene() {
        CallScenario callScenario = new CallScenario();
        callScenario.setActName("场景名称11333");
        callScenario.setActContent("场景内容33");
        callScenario.setAmTime("09:00-12:00");
        callScenario.setPmTime("13:30-18:00");
        callScenario.setDailyNumCall("2");
        callScenario.setNoCallRetry("5");
        CallResponse response = sendRequest(CREATE_SCENE_API_ENDPOINT, HttpMethod.POST, callScenario);
        System.out.println(response.toString());
    }

    /**
     * 获取场景列表
     */
    @org.junit.Test
    public void getSceneList() {
        CallResponse response = sendRequest(SCENE_API_ENDPOINT, HttpMethod.POST, "");
        System.out.println(response.toString());
    }


    /**
     * 任务执行接口
     */
    @org.junit.Test
    public void executeTask() {
        CallScene callScene = new CallScene();
        callScene.setActId("1691372076927025152");

        CallScene.Task task = new CallScene.Task();
        List<CallScene.Task> taskList = new ArrayList<>();
        task.setTaskId("1111111111111111");
        task.setUser_phone("15085938784");
        taskList.add(task);
        callScene.setTasks(taskList);

        CallResponse response = sendRequest(TASK_API_ENDPOINT, HttpMethod.POST, callScene);
        System.out.println(response.toString());

    }

    /**
     * 获取执行结果
     */
    @org.junit.Test
    public void getExecutionResult() {
        List<String> taskIdList = new ArrayList<>();
        TaskList taskList = new TaskList();
        String taskId = "1111111111111111";
        taskIdList.add(taskId);
        taskList.setTaskIdList(taskIdList);
        CallResponse response = sendRequest(RESULT_API_ENDPOINT, HttpMethod.POST, taskList);
        System.out.println("响应内容："+response.toString());

    }

    /**
     * 发送请求
     *
     * @param endpoint    端点
     * @param method      方法
     * @param requestBody 请求体
     * @return {@link CallResponse}
     */
    private CallResponse sendRequest(String endpoint, HttpMethod method, Object requestBody) {
        IntelligentCallParameters parameters = new IntelligentCallParameters(APPID, String.valueOf(System.currentTimeMillis() / 1000));
        encryptionParameters(parameters, requestBody);
        generateSign(parameters);
        HttpHeaders headers = createHeaders(MediaType.APPLICATION_JSON);
        HttpEntity<String> requestEntity = new HttpEntity<>(toJsonString(parameters), headers);
        System.out.println("请求体："+requestEntity.getBody());
        String responseBody = restTemplate.exchange(URL + endpoint, method, requestEntity, String.class).getBody();
        return parseCallResponse(responseBody);
    }

    private static HttpHeaders createHeaders(MediaType mediaType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);
        return headers;
    }

    private static String toJsonString(Object object) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(object).replace("timestamp", "timeStamp");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static CallResponse parseCallResponse(String body) {
        return JSON.parseObject(body, new TypeReference<CallResponse>() {
        });
    }

    /**
     * 生成签名
     *
     * @param parameters 参数
     */
    private static void generateSign(IntelligentCallParameters parameters) {
        Map<String, String> stringStringMap = SignUtils.convertToIntelligentCallParameters(parameters);
        String signature = SignUtils.generateSignature(stringStringMap, PRIVATE_KEY);
        parameters.setSign(signature);
    }

    /**
     * 加密参数
     */
    private static void encryptionParameters(IntelligentCallParameters parameters, Object object) {
        ObjectMapper mapper = new ObjectMapper();
        String json = "";
        try {
            json = mapper.writeValueAsString(object);
            System.out.println("请求参数："+json);
        } catch (JsonProcessingException e) {
            e.getMessage();
        }
        String encryption = AESUtils.encryption(json, PRIVATE_KEY);
        parameters.setParam(encryption);
    }

}
